package com.take.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.take.common.BaseContext;
import com.take.common.R;
import com.take.entity.Employee;
import com.take.service.EmployeeService;
import com.take.utils.JwtTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "员工管理模块")
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    JwtTokenUtils jwtTokenUtils;

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @ApiOperation(value = "员工登录")
    @PostMapping("/login")
    public R<Map> login(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("员工登录：{}", employee.toString());
        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("登录失败，用户不存在");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败，密码错误");
        }

        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //6、登录成功，将员工id存入Session并返回登录成功结果
        //  request.getSession().setAttribute("employee",emp.getId());
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", (Long) emp.getId());
        payload.put("username", emp.getUsername());

        //生成JWT的令牌
        String token = jwtTokenUtils.generateJwt(payload);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);//响应token
        map.put("id", emp.getId());//响应id
        return R.success(map);
    }

    /**
     * 员工退出
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "员工退出")
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @ApiOperation(value = "新增员工（必须的信息：用户账号、员工昵称、手机号，自动设置初始密码123456）")
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        log.info("新增员工，员工信息：{}", employee.toString());

        //获取当前员工的id
        long currentId = BaseContext.getCurrentId();
        if(currentId!=1){
            return R.error("新增员工账号只能由管理员操作");
        }

        //检查信息
        if (employee.getUsername() == null || employee.getUsername().trim().length()==0) {
            return R.error("缺少用户账号！");
        }

        if (employee.getName() == null || employee.getName().trim().length()==0) {
            return R.error("缺少员工昵称（员工姓名）！");
        }

        if (employee.getPhone() == null || employee.getPhone().trim().length()==0) {
            return R.error("缺少员工手机号！");
        }

        if (employee.getIdNumber() == null || employee.getIdNumber().trim().length()==0) {
            return R.error("缺少员工号！");
        }
        //检查账号是否重复
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee empUsernameInUse = employeeService.getOne(queryWrapper);
        if (empUsernameInUse != null) {
            return R.error("员工账号重复，请重新输入！");
        }

        //检查员工号是否重复
        LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Employee::getIdNumber, employee.getIdNumber());
        Employee empIdNumberInUse = employeeService.getOne(queryWrapper2);
        if (empIdNumberInUse != null) {
            return R.error("员工号重复，请重新输入！");
        }


        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1); //默认是启用
        // 不需要新增用户的有头像
        employee.setAvatar(null);
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        employeeService.save(employee);

        return R.success("新增员工成功，初始密码为123456");
    }

    /**
     * 员工信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "员工信息分页查询")
    @GetMapping("/page")
    public R<Page> page(@RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "10") int pageSize,
                        String name, Integer status) {
        log.info("员工分页查询 page = {},pageSize = {},name = {},status = {}", page, pageSize, "name", status);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(status!=null,Employee::getStatus,status);
        //添加过滤条件(排除id=1的admin)
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name)
                .and(w -> w.ne(Employee::getId, 1));

        //添加排序条件
        queryWrapper.orderByAsc(Employee::getId);

        //执行查询
        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 根据id修改员工信息
     *
     * @param employee
     * @return
     */
    @ApiOperation(value = "修改员工信息（仅支持修改自己的：昵称、身份证号、手机号、性别、头像）")
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        log.info(employee.toString());
        //检查信息
        if (employee.getName() == null) {
            return R.error("用户必须有昵称");
        } else if (employee.getName().length() < 2 || employee.getName().length() > 10) {
            return R.error("用户的昵称至少2个字符,最多10个字符");
        } else if (employee.getIdNumber() != null && employee.getIdNumber().length() > 18) {
            return R.error("员工号格式不正确，长度不超过18字符");
        }

        //不允许通过此方法修改 username / password / status
        //获取当前员工的id
        Long empId = BaseContext.getCurrentId();
        log.info("线程id为：{}", empId);
        //如果empId是null，则说明当前线程没有登录
        if (empId == null) {
            return R.error("修改失败！登录身份失效！");
        }
        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Employee::getId, empId);
        updateWrapper.set(employee.getName() != null, Employee::getName, employee.getName());
        updateWrapper.set(employee.getIdNumber() != null, Employee::getIdNumber, employee.getIdNumber());
        updateWrapper.set(employee.getPhone() != null, Employee::getPhone, employee.getPhone());
        updateWrapper.set(employee.getSex() != null, Employee::getSex, employee.getSex());
        updateWrapper.set(employee.getAvatar() != null, Employee::getAvatar, employee.getAvatar());
        updateWrapper.set(Employee::getUpdateTime, LocalDateTime.now());

        employeeService.update(updateWrapper);

        return R.success("员工信息修改成功");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id查询员工信息")
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }


    @ApiOperation(value = "批量重置员工密码为123456")
    @PostMapping("/reset")
    public R<String> resetPasswordBatch(@RequestParam(value = "ids") Long[] ids) {
        log.info("重置员工 employeeId = {}", ids);

        employeeService.resetPasswordBatch(ids);
        return R.success("重置密码成功");
    }


    @ApiOperation(value = "员工修改密码")
    @PatchMapping("/updatePwd")
    public R updatePwd(String oldPwd, String newPwd, String rePwd) {
        //1.校验参数
        if (!org.springframework.util.StringUtils.hasLength(oldPwd) || !org.springframework.util.StringUtils.hasLength(newPwd) || !org.springframework.util.StringUtils.hasLength(rePwd)) {
            return R.error("缺少必要的密码参数");
        }

        //原密码是否正确
        //调用userService根据用户名拿到原密码,再和old_pwd比对
        Long empId = BaseContext.getCurrentId();
        Employee employee = employeeService.getById(empId);
        String oldPwdEncryption = DigestUtils.md5DigestAsHex(oldPwd.getBytes());
        if (!employee.getPassword().equals(oldPwdEncryption)) {
            return R.error("原密码不正确");
        }

        //newPwd和rePwd是否一样
        if (!rePwd.equals(newPwd)) {
            return R.error("两次填写的新密码不一样");
        }

        //2.调用service完成密码更新(密码需要加密)
        String newPwdEncryption = DigestUtils.md5DigestAsHex(newPwd.getBytes());
        employeeService.updatePasswd(empId, newPwdEncryption);

        return R.success("密码修改成功！");
    }

    @ApiOperation(value = "启用/禁用员工（status=1-启用；0-禁用）")
    @PutMapping("/{id}")
    public R<String> updateEmployeeStatus( @PathVariable Long id ,@RequestParam(value = "status") Integer status) {
        log.info("启用/禁用员工 employeeId = {}", id);

        //获取当前员工的id
        long currentId = BaseContext.getCurrentId();
        if(currentId!=1){
            return R.error("启用/禁用员工账号只能由管理员操作");
        }

        if (status == null ) {
            return R.error("缺少状态码参数（1-启用；0-禁用）");
        }

        if (id == null ) {
            return R.error("缺少员工id参数");
        }

        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Employee::getId, id);
        updateWrapper.set(status!= null, Employee::getStatus, status);
        employeeService.update(updateWrapper);

        return R.success("员工账号状态修改成功");
    }

}
